package com.skeyedu.utils;

import com.skeyedu.pojo.Users;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * @Description 邮件工具类
 * @Author 羽落陌殇
 * @Date 2021/7/22 17:00
 * @Version 1.0.0
 */
public class SendMail extends Thread {
    // 发件人
    private String form = "1971636824@qq.com";
    // 邮箱的用户名
    private String username = "1971636824@qq.com";
    // 邮箱的授权码
    private String password = "zylxrinierazfbie";
    // 发送邮箱的服务器地址
    private String host = "smtp.qq.com";

    private Users users = null;
    public SendMail (Users users) {
        this.users = users;
    }

    @Override
    public void run() {
        try {
            Properties properties = new Properties();
            properties.setProperty("mail.host", host); // 设置网易邮件服务器
            properties.setProperty("mail.transport.protocol", "smtp"); // 设置邮件发送协议
            properties.setProperty("mail.smtp.auth", "true"); // 设置需要验证用户名和密码

            // 关于 QQ 邮箱, 需要设置SSL加密
            MailSSLSocketFactory factory = new MailSSLSocketFactory();
            factory.setTrustAllHosts(true); // 设置可信任的主机, 此处我们设置所有主机可信
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", factory);

            // 创建 JavaMail 的五个步骤
            // 1、创建定义整个应用程序所需的环境信息的 Session 对象
            Session session = Session.getInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            // 2、通过 Session 获得 Transport 对象
            Transport transport = session.getTransport();
            // 3、使用邮箱的用户名和授权码连上邮件服务器
            transport.connect(host, username, password);
            // 4、创建邮件
            Message message = new MimeMessage(session);
            // 设置邮件的发件人
            message.setFrom(new InternetAddress(form));
            // 设置邮件主题
            message.setSubject("浙江天眼系统温馨提示");
            // 设置收件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(users.getEmail()));
            // 设置邮件内容
            message.setContent("<h1 style='color: red; font-size: 24px; font-weight:600;'>恭喜您注册成功!</h1><br><a href='http://localhost:8080/Servlet_Day09_Mail/user.do?method=active&uid="+users.getId()+"&status="+users.getStatus()+"'>请点击此连接激活账户</a>",
                    "text/html; charset=UTF-8");

            // 5、发送邮件
            transport.sendMessage(message, message.getAllRecipients());
            // 6、关闭连接
            transport.close();
        } catch (GeneralSecurityException | MessagingException e) {
            e.printStackTrace();
        }
    }
}
